import traceback
from flask import Blueprint, request
from flask_restful import reqparse, Resource, Api, marshal_with,fields
from ....models.database import db, auto_commit
from ....decorator.consolejwt import console_token
from ...res import output_json
from ....libs.unit import formatDate
from ....models.common.log import Log


# 蓝图并放入 restful
log = Blueprint('log', __name__, url_prefix='/c-api/log')
api = Api(log)

# 统一封装 API 返回值
@api.representation('application/json')
def out_json(data, code, headers=None):
    return output_json(data, code, headers=None)


# 封装返回的数据格式
resource_fields = {
    'count': fields.Integer,
    'list': fields.List(fields.Nested({
        'id':fields.Integer,
        'user': fields.String,
        'action_name': fields.String,
        'method': fields.String,
        'url': fields.String,
        'data': fields.String,
        'created_at': formatDate(attribute='created_at')
    }))
}


class ListLog(Resource):
    @console_token
    @marshal_with(resource_fields, envelope='resource')
    def get(self):
        # 请求验证
        parser = reqparse.RequestParser()
        parser.add_argument('page', type=int,
                            help=' 页码必须填写', location=['form', 'args'], required=True, action='store')
        args = parser.parse_args()
        page = args.get('page')
        # 添加搜索条件
        start_time = request.values.get('starttime',None)
        end_time = request.values.get('endtime',None)
        admin_id = request.values.get('admin_id',None)
        with auto_commit():
            lists = Log.query
            if start_time != None and end_time != None:
                lists = lists.filter(Log.created_at >= start_time,Log.created_at <= end_time)
            if admin_id != None:
                lists = lists.filter(Log.admin_id == admin_id)
            lists = lists.order_by(Log.id.desc()).paginate(page, per_page=10, error_out=False)
            c = {'count': lists.total, 'list': lists.items}
        return c


api.add_resource(ListLog, '/list')
